var POST_PERSONNEL_CHANGE_ADD = function () {
	this.init();
}

POST_PERSONNEL_CHANGE_ADD.prototype.init = function () {
	var self = this;
	WASP_WIDGET.triggerSelectOnEmpId("#newPersonnelId",{"multiple": true, "cleanDele": true});
	WASP_WIDGET.triggerDateStyleWithYMD("#effctiveDate");
	
	$('#postId').select2({placeholder: "变更岗位"});
	WASP_WIDGET.triggerSelectOnEmpId("#oldPersonnelIds"/*,{"multiple": true, "queryDimission": true,cleanDele: true}*/);
	
	$("#postId").change(function () {
    	$("#options-body").find('.multiselect-item').remove();
    	$("#selected-body").find('.multiselect-item').remove();
    });
	
	self.expend();
	self.mulitsltTirgger();
	
	$("#postPersonnelChangeAddForm").validate({
		focusCleanup : true
    });
	
	$("#postId").bind('change', function(){
		$("#postId").valid();
		var $type = $("#postId").val() && $("#postId").val().split("&&")[1];
		if ($type && $type == 'MANAGER') {
			$("#prjSNameDiv").hide();
			$("#companyNameDiv").show();
		} else {
			$("#prjSNameDiv").show();
			$("#companyNameDiv").hide();
		}
	});
	$("#newPersonnelId").bind('change', function(){
		$("#newPersonnelId").valid();
	});
	$("#effctiveDate").bind('change', function(){
		$("#effctiveDate").valid();
	});
}

POST_PERSONNEL_CHANGE_ADD.prototype.expend = function () {
	var self = this;
	self.queryResouceList = function () {
		var $prjSName = $.trim($("#prjSName").val());
		var $companyName = $.trim($("#companyName").val());
		var $oldPersonnelId = $.trim($("#oldPersonnelIds").val());
		var $postId = $("#postId").val().split("&&")[0];
		var $type = $("#postId").val().split("&&")[1];
		
		var resourceIds = "";
		var $list = $("#selected-body").find(".multiselect-item");//获取已选项div
		if($list && $list.length>0){
			for(var j=0;j<$list.length;j++){
				var item=$($list[j]);
				resourceIds += item.attr("id")+",";
			}
		}
		
		if($list.length > 500){
			ctools.alert("已选资源超过500条","","warning");
			return ;
		}
		
		if ($postId == null || $postId == "") {
			ctools.alert("请选择需要变更的岗位!","","warning");
			return ;
		}
		$.ajax({
			url: POST_PERSONNEL_CHANGE_ADD_PATH + "queryResouceListByCondition.do",
			data: {
				"sp[postId]": $postId,
				"sp[type]": $type,
				"sp[prjSName]": $prjSName,
				"sp[oldPersonnelId]": $oldPersonnelId,
				"sp[companyName]": $companyName,
				"sp[resourceIds]": resourceIds
			},
			dataType: "json",
			type: "post",
			async: true,
			cache: false,
			success: function (data) {
				$("#options-body").find('.multiselect-item').remove();
				if(data.length==0){
				    ctools.alert("未搜索到符合条件的资源列表!","","warning");
				    return false;
			    }
			   
				for(var i=0;i<data.length;i++){
					var oldName = data[i]['PERSONNELNAMES'] && data[i]['PERSONNELNAMES'] || "";
					var oldNames = data[i]['PERSONNELNAMES'] && ': ' + data[i]['PERSONNELNAMES'] + "（岗位生效人员）" || "";
					var oldIds = data[i]['PERSONNELIDS'] && data[i]['PERSONNELIDS'] || "";
					var $html='<div class="multiselect-item" id="' + data[i]['RESOURCEID'] + '">'+ data[i]['RESOURCENAME'] + oldNames + '<input type="hidden" id="' + oldIds + '" value = "' + oldName + '" /></div>';
					$("#options-body").append($html);
				}
			},
			error: function (jqXHR, textStatus, errorThrown) {
				$("#options-body").find('.multiselect-item').remove();
				ctools.alert("查询变更资源列表出错" + textStatus, "", "warning");
			}
		});
		
	};
	self.comfirm = function () {
		self.validate();
		if ($("#postPersonnelChangeAddForm").valid()) {
			$("#confirmTable tr:not(:first)").empty();
			var $remark = $("#remark").val();
			var $effctiveDate = $("#effctiveDate").val();
			var $postName = $.trim($("#postId option:selected").text());
			var $resourceIds = "";
			var $list = $("#selected-body").find(".multiselect-item");//获取已选项div
			var content = "";
			for (var i = 0; i < $list.length; i++) {
				var item = $($list[i]);
				var $newPersonnelNames = "";
				var reslist = $("#newPersonnelId").select2("data");
				for (var j = 0; j < reslist.length; j++) {
					if (!$newPersonnelNames) {
						$newPersonnelNames = reslist[j].text;
					} else {
						$newPersonnelNames += "," + reslist[j].text;
					}
				}
				
				content+="<tr>"+
				"<td>" + item.text() + "</td>"+  //资源名称
				"<td>" + $postName + "</td>"+ //岗位
				"<td>" + $effctiveDate + "</td>"+ //生效日
				"<td>" + item.find("input").val() + "</td>"+ //变更前岗位人员
				"<td>" + $newPersonnelNames + "</td>"+//变更后岗位人员
				"<td>" + $remark + "</td>"+//变更原因
				"</tr>";
				
				
			}
			$("#confirmTable tr[id='header']").after(content);
			$("#step2").show("slow");
			$("#step1").hide("slow");
		} else {
			ctools.alert("请完善信息","","warning");
		}
	};
	self.backSelect = function () {
		$("table tr[id^='content']").remove();
		$("#step2").hide("slow");
		$("#step1").show("slow");
	};
	self.validate = function () {
		$("#newPersonnelId").rules("remove");
		$("#postId").rules("remove");
		$("#effctiveDate").rules("remove");
		$("#resourceId").rules("remove");
		$("#remark").rules("remove");
		
		$("#newPersonnelId").rules("add", {
			required: true, messages: {required: "请选择变更后的岗位人员"}
		});
		$("#postId").rules("add", {
			required: true, messages: {required: "请选择变更岗位"}
		});
		$("#effctiveDate").rules("add", {
			required: true, messages: {required: "请选择变更生效日"}
		});
		$("#resourceId").rules("add", {
			checkSelected: true, maxlength : 500, messages: {checkSelected: "已选资源列表不能为空", maxlength: "已选资源超过500条"}
		});
		$("#remark").rules("add", {
			maxlength4Byte: 500, messages: {maxlength4Byte: "最大长度不可超过2000字符"}
		});
	};
	self.clearQueryCondition = function () {
		$("#prjSName").val(null);
		$("#companyName").val(null);
		$("#oldPersonnelIds").val(null).trigger("change");
	};
	self.mulitsltTirgger = function () {
		$('#multiselect').on('click', '.multiselect-item', function() {
	        $(this).toggleClass('active');
	    }).on('click', '.multiselect-toright', function() {
	        var $selectArea = $('.multiselect');
	        $selectArea.find('#options-body')
	            .find(".multiselect-item")
	            .removeClass('active')
	            .appendTo($selectArea.find('#selected-body'));
	    })
	    .on('click', '.multiselect-goright', function() {
	        var $selectArea = $('#options-body');
	        var $rightArea = $('#selected-body');
	        $selectArea
	            .find(".multiselect-item.active")
	            .appendTo($rightArea);
	    })
	    .on('click', '.multiselect-toleft', function() {
	        var $selectArea = $('.multiselect');
	        $selectArea.find('#selected-body')
	            .find(".multiselect-item")
	            .removeClass('active')
	            .appendTo($selectArea.find('#options-body'));
	    })
	    .on('click', '.multiselect-goleft', function() {
	        var $selectArea = $('#options-body');
	        var $rightArea = $('#selected-body');
	        $rightArea
	            .find(".multiselect-item.active")
	            .appendTo($selectArea);
	    });
	};
	self.savePostPersonnelChange = function () {
		SubmitAndPreventSecond("postPersonnelChangeAddForm", function () {
			var canSubmit = false;
			var $postId = $("#postId").val().split("&&")[0];
			var $resourceId = "";
			var $effctiveDate = $("#effctiveDate").val();
			var $postRank = $("#postId").val().split("&&")[1];
			
			var $list=$("#selected-body").find(".multiselect-item");//获取已选项div
			if($list && $list.length>0){
				for(var j=0;j<$list.length;j++){
					var item=$($list[j]);
					$resourceId += item.attr("id")+",";
				}
			}
			
			$.ajax({
				url: POST_PERSONNEL_CHANGE_ADD_PATH + "checkEffctiveDateUnique.do",
				type: "POST",
				dataType: "JSON",
				data: {
					postId: $postId,
					resourceId: $resourceId,
					effctiveDate: $effctiveDate,
					postRank: $postRank
				},
				async: false,
				success: function (data) {
					if (data && data.success) {
						canSubmit = true;
					} else {
						ctools.alert(data && data.message + "已存在该生效日变更","","warning");
					}
				},
				error: function () {
					ctools.alert("校验生效日是否重复出错!","","error");
				}
			})
			return canSubmit;
		}, true);
	}
}

$.validator.addMethod("checkSelected",function(value,element,params){
	var resourceId = "";
	var $list = $("#selected-body").find(".multiselect-item");//获取已选项div
	if($list.length > 0){
		for(var j = 0; j < $list.length; j++){
			var item = $($list[j]);
			var id = item.attr("id");
			if (!resourceId) {
				resourceId = id;
			} else {
				resourceId += "," + id;
			}
		}
	}else{
		return false;
	}
	$("#resourceId").val(resourceId);
	return true;
}, "");

$.validator.addMethod("maxlength",function(value,element,params){
	var resourceId = "";
	var $list = $("#selected-body").find(".multiselect-item");//获取已选项div
	if($list.length > params){
		return false;
	}
	return true;
}, "");
